package com.baselibrary.test.ui;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.baselibrary.libs.Utils.log.LogUtils;
import com.baselibrary.libs.base.baseActivity.BaseActivity;
import com.baselibrary.test.R;

import mabeijianxi.camera.MediaRecorderActivity;
import mabeijianxi.camera.util.DeviceUtils;
import mabeijianxi.camera.util.StringUtils;
import mabeijianxi.camera.views.SurfaceVideoView;

public class VideoPlayerActivity extends BaseActivity implements
        SurfaceVideoView.OnPlayStateListener, MediaPlayer.OnErrorListener,
        MediaPlayer.OnPreparedListener, View.OnClickListener, MediaPlayer.OnCompletionListener,
        MediaPlayer.OnInfoListener {

    /**
     * 播放控件
     */
    private SurfaceVideoView mVideoView;
    /**
     * 暂停按钮
     */
    private View mPlayerStatus;
    private View mLoading;

    /**
     * 播放路径
     */
    private String mPath;
    /**
     * 是否需要回复播放
     */
    private boolean mNeedResume;
    private int displayWidth;
    private int displayHeight;
    private UrlBroadcastReceiver mUrlBroadcastReceiver;
    private String videoUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initReceiver();
    }

    @Override
    public int getlayouXML() {
        return R.layout.activity_video_player;
    }

    @Override
    public void initP() {

    }

    @Override
    public void initView() {

        // 防止锁屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        mPath = getIntent().getStringExtra("path");
        if (StringUtils.isEmpty(mPath)) {
            finish();
            return;
        }
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        displayWidth = displayMetrics.widthPixels;
        displayHeight = displayMetrics.heightPixels;
        mVideoView = (SurfaceVideoView) findViewById(R.id.videoview);

        RelativeLayout.LayoutParams  layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,(int) (displayHeight * 0.75f + 0.5f) );
        mVideoView.setLayoutParams(layoutParams);

        //int screenWidth = getScreenWidth(this);
        //int videoHight = (int) (screenWidth / (MediaRecorderBase.SMALL_VIDEO_WIDTH / (MediaRecorderBase.SMALL_VIDEO_HEIGHT * 1.0f)));
//        mVideoView.getLayoutParams().height = videoHight;
//        mVideoView.requestLayout();

        mPlayerStatus = findViewById(R.id.play_status);
        mLoading = findViewById(R.id.loading);

        mVideoView.setOnPreparedListener(this);
        mVideoView.setOnPlayStateListener(this);
        mVideoView.setOnErrorListener(this);
        //mVideoView.setOnClickListener(this);
        mVideoView.setOnInfoListener(this);
        mVideoView.setOnCompletionListener(this);

//		mVideoView.getLayoutParams().height = DeviceUtils.getScreenWidth(this);

        findViewById(R.id.root).setOnClickListener(this);
        mVideoView.setVideoPath(mPath);
    }
    public int getScreenWidth(Activity context) {
        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
        int W = mDisplayMetrics.widthPixels;
        return W;
    }
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        switch (event.getKeyCode()) {// 跟随系统音量走
            case KeyEvent.KEYCODE_VOLUME_DOWN:
            case KeyEvent.KEYCODE_VOLUME_UP:
                mVideoView.dispatchKeyEvent(this, event);
                break;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void initData() {

    }

    @Override
    public void initListener() {

    }
    public void  openVideo(){
        //如果是有视频
        if (null!=videoUri){
            LogUtils.i("路径是"+videoUri);
            // RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) uploadpictures_xd_1.getLayoutParams();



            //int[] measure = UtilsMeasure.measure(uploadpictures_xd_1);
            RelativeLayout.LayoutParams  layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,(int) (displayHeight * 0.75f + 0.5f) );
            mVideoView.setLayoutParams(layoutParams);

//            //设置跟 按钮一样大
//            mUploadpictures_mvv.setLayoutParams(layoutParams);


            //设置路径
            mVideoView.setVideoPath(videoUri);
            if (mVideoView.isPlaying()) {
                mVideoView.pause();
            }
        }
    }
    @Override
    public void onCompletion(MediaPlayer mp) {
        if (!isFinishing())
            mVideoView.reOpen();
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        if (!isFinishing()) {
            // 播放失败
        }
        finish();
        return false;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        switch (what) {
            case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
                // 音频和视频数据不正确
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                if (!isFinishing())
                    mVideoView.pause();
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                if (!isFinishing())
                    mVideoView.start();
                break;
            case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                if (DeviceUtils.hasJellyBean()) {
                    mVideoView.setBackground(null);
                } else {
                    mVideoView.setBackgroundDrawable(null);
                }
                break;
        }
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mVideoView.setVolume(SurfaceVideoView.getSystemVolumn(this));
        mVideoView.start();
        // new Handler().postDelayed(new Runnable() {
        //
        // @SuppressWarnings("deprecation")
        // @Override
        // public void run() {
        // if (DeviceUtils.hasJellyBean()) {
        // mVideoView.setBackground(null);
        // } else {
        // mVideoView.setBackgroundDrawable(null);
        // }
        // }
        // }, 300);
        mLoading.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.videoview:
            case R.id.root:
               // finish();
                if (mVideoView.isPlaying()){
                    mVideoView.pause();

                }else{
                    mVideoView.start();
                }
                break;
        }
    }

    @Override
    public void onStateChanged(boolean isPlaying) {
        mPlayerStatus.setVisibility(isPlaying ? View.GONE : View.VISIBLE);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mVideoView != null && mNeedResume) {
            mNeedResume = false;
            if (mVideoView.isRelease())
                mVideoView.reOpen();
            else
                mVideoView.start();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mVideoView != null) {
            if (mVideoView.isPlaying()) {
                mNeedResume = true;
                mVideoView.pause();
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (mVideoView != null) {
            mVideoView.release();
            mVideoView = null;
        }
        unregisterReceiver(mUrlBroadcastReceiver);
        super.onDestroy();
    }

    /**
     * 更新界面信息的广播
     */
    public void initReceiver(){
        mUrlBroadcastReceiver = new UrlBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("VIDEO_URI");
        registerReceiver(mUrlBroadcastReceiver, intentFilter);
    }

    class UrlBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(final Context context, Intent intent) {
            //路径
            videoUri = intent.getStringExtra(MediaRecorderActivity.VIDEO_URI);
            LogUtils.i("回来的数据是"+ videoUri);

            openVideo();
//            FileInputStream soundStream = null;
//            try {
//                soundStream = new FileInputStream(videoUri);
//                //String fileName = videoUri.substring(videoUri.lastIndexOf("/") + 1);
//                String fileName = "xingxingdai_loan_video1.mp4";
//                LogUtils.i("转换完的语音格式是"+fileName);
//                //发送请求 把语音地址发上去
//                // String url = "http://192.168.4.102:8080/my/upload";
//                String token = Share.getToken(context);
//                String loan_area = Share.getString(context, "loan_area");
//                String xingxing = "xingxingdai";
//
//                String url = SyncStateContract.Constants.up_image_url+"?"+"app="+xingxing+"&loan_area="+loan_area+"&loan_id="+token;
//
//
//                HttpMultipartPost post = new HttpMultipartPost(context, url, soundStream, fileName);
//                post.setCallBackMsg(new HttpMultipartPost.CallBackMsg() {
//                    @Override
//                    public void msg(JSONObject msg) {
//                        if (null!=msg){
//                            if (0==msg.getIntValue("result")){
//                                UtilsToast.showToast(context, msg.getString("message"));
//                                Tag = false;
//                                return;
//                            }else{
//                                UtilsToast.showToast(context, "上传成功");
//                            }
//                            LogUtils.i("视频"+msg);
//                            openVideo();
//                        }
//
//                    }
//                });
//                post.setCallBack(new HttpMultipartPost.CallBack() {
//                    @Override
//                    public void update(Integer i) {
//                        LogUtils.i("上传进度"+i);
//                        UtilsToast.showToast(context, "上传中"+i+"%");
//                    }
//                });
//                post.execute();
//                //post.execute(new HttpMultipartPost.Param("time", String.valueOf(Math.round(mTime))));
//
//
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }



        }
    }
}
